package com.yueban.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.yueban.R;
import com.yueban.adapter.JoinListAdaper;
import com.yueban.model.BaseResponse;
import com.yueban.model.ResultCode;
import com.yueban.model.User;
import com.yueban.net.NetWorkController;
import com.yueban.util.SPManager;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class JoinActivity extends AppCompatActivity {

    private Button join;
    private ProgressBar progressBar;
    private long activityId;

    private long userId;
    private boolean hasjoin;

    private JoinListAdaper joinListAdaper;
    private ArrayList<User> users;
    private SPManager spManager;

    private NetWorkController netWorkController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join);

        Toolbar toolbar = (Toolbar) findViewById(R.id.join_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        //添加返回键
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("参与的人");
        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        join = (Button) findViewById(R.id.join_submit);
        progressBar = (ProgressBar) findViewById(R.id.join_progress);

        Intent intent = getIntent();
        activityId = intent.getLongExtra("activityId", -1);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.join_ryv);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        users = new ArrayList<>();
        joinListAdaper = new JoinListAdaper(users);
        recyclerView.setAdapter(joinListAdaper);

        join.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (hasjoin) {
                    showPragressBar(true);
                    joinActivity(2);
                } else {
                    showPragressBar(true);
                    joinActivity(1);
                }
            }
        });

        spManager = new SPManager(getApplicationContext());
        this.userId = spManager.getUserId();
        netWorkController = new NetWorkController();
        //开启进度条，查询参与人列表
        showPragressBar(true);
        getJoinList();

    }

    private void getJoinList() {
        netWorkController.getJoinList(activityId).subscribe(new Observer<BaseResponse<List<User>>>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull BaseResponse<List<User>> listBaseResponse) {
                if (listBaseResponse.getStatus() == ResultCode.SUCCESS) {
                    List<User> joinList = listBaseResponse.getData();
                    if (joinList != null) {
                        users.addAll(joinList);
                        //查询自己是否参与
                        queryHasJoin();

                    }
                    joinListAdaper.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                showPragressBar(false);
                Toast.makeText(JoinActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
                showPragressBar(false);
            }
        });
    }

    private void joinActivity(final int action) {

        netWorkController.joinActivity(activityId, userId, action).subscribe(new Observer<BaseResponse<Boolean>>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull BaseResponse<Boolean> booleanBaseResponse) {
                if (booleanBaseResponse.getStatus() == ResultCode.SUCCESS) {
                    switch (action) {
                        //参与
                        case 1:
                            hasjoin = true;
                            join.setText("取消参与");
                            addMetoJoinLlist();
                            Snackbar.make(join, "参与成功", Snackbar.LENGTH_LONG).show();
                            break;
                        //退出
                        case 2:
                            hasjoin = false;
                            join.setText("参与");
                            deleteMeFromJoinList();
                            Snackbar.make(join, "退出该活动", Snackbar.LENGTH_LONG).show();
                            break;
                    }
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                showPragressBar(false);
                Toast.makeText(JoinActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
                showPragressBar(false);
            }
        });
    }

    private void queryHasJoin() {
        for (User user : users) {
            if (user.getId() == userId) {
                hasjoin = true;
                join.setText("取消参与");
                return;
            }
        }
        hasjoin = false;
        join.setText("参与");
    }

    private void addMetoJoinLlist() {
        User user = new User();
        user.setName(spManager.getUserName());
        user.setId(userId);
        users.add(user);
        joinListAdaper.notifyDataSetChanged();
    }

    private void deleteMeFromJoinList() {
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getId() == userId) {
                users.remove(i);
                joinListAdaper.notifyDataSetChanged();
                return;
            }
        }
    }

    private void showPragressBar(boolean show) {
        join.setVisibility(show ? View.GONE : View.VISIBLE);
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
    }

}
